import { ApiCall } from "tsrpc";
import { ReqCreateEquip, ResCreateEquip } from "../../shared/api_client/mod/PtlCreateEquip";
import { Item } from "../../shared/face/index";
import { ItemType, quality } from "../../shared/face/enums";
import { ComType } from "../../core/tool/component";
import bag_component from "../../component/bag_component";
import player from "../../core/rpg/entity/player";
import EquipManage, { EquipTemplate } from "../../core/manage/EquipManage";
import sdk from '../../core/index';

export default async function (call: ApiCall<ReqCreateEquip, ResCreateEquip>) {
    try {
        // 获取当前用户
        const user = call.req._player as player;
        if (!user) {
            call.error('用户未登录');
            return;
        }

        // 获取背包组件
        const bagCom = user.getComponent(ComType.背包) as bag_component;
        if (!bagCom) {
            call.error('背包组件未找到');
            return;
        }

        // 构建装备模板数据
        const equipTemplate: EquipTemplate = {
            strengthenLevel:1,
            id: '',
            uuid: sdk.tool.common.uuid,
            count: 1,
            icon: call.req.icon,
            name: call.req.name,
            emoji: "🗡️",
            sys: call.req.sys,
            type: call.req.type,
            job: call.req.job,
            quality: {
                min: quality.F,
                max: quality.SSR
            },
            solt_type: call.req.solt_type,
            desc: call.req.desc,
            source: call.req.source,
            creator: user.id,
            attribute: [],
            skill: [],
            createTime: 0,
            updateTime: 0
        };

        // 保存装备模板到数据库
        const templateId = await EquipManage.saveTemplate(equipTemplate, user.id);

        // 构建Item对象（直接可用）
        const equipItem: Item = sdk.prop.createProp({
            type: ItemType.装备,
            id: templateId,
            count: 1
        });

        // 可选：直接发放到背包
        // bagCom.addItem(equipItem);

        // 返回成功响应
        call.succ({
            message: `成功创建装备模板并生成装备: ${call.req.name}`,
            equipId: equipItem.id,
            templateId: templateId
        });

    } catch (error) {
        console.error('创建装备失败:', error);
        call.error('创建装备失败: ' + (error as Error).message);
    }
}
